package com.reguang.config;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.reguang.enums.ResultCode;
import com.reguang.exception.CacheException;
import com.reguang.exception.TokenException;
import com.reguang.utils.ObjectUtils;
import com.reguang.utils.RedisOperator;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * <p>Title: TokenConfig</p>
 * <p>Description: token工具类</p>
 * @author weibiao
 * @date 2019年7月1日
 */
@Component
@Slf4j
public class TokenConfig {

	@Autowired
	private RedisOperator redisOperator;

	public String getCurrentTokenVar(String key, HttpServletRequest request) throws Exception {
		String token = request.getHeader("token");
		if (ObjectUtils.isNull(token))
			throw new TokenException();
		String data = redisOperator.get(token);
		log.info("【缓存信息】，result: {}", data);
		if (ObjectUtils.isNull(data)) {
			throw new CacheException();
		} else {
			JSONObject jsonObject = JSONObject.parseObject(data);
			if (jsonObject.containsKey(key)) {
				return jsonObject.getString(key);
			} else {
				throw new TokenException(ResultCode.USER_TOKEN_NOT_FOUND);
			}
		}
	}

	public Integer getCurrentUid(HttpServletRequest request) throws Exception {
		return Integer.parseInt(this.getCurrentTokenVar("uid", request));
	}

	public Boolean verifyToken(String token) {
		String data = redisOperator.get(token);
		return ObjectUtils.isNotNull(data);
	}
}
